<template>
	<el-drawer
	  v-model="dialog.visible"
	  :title="dialog.title"
	  append-to-body
	  @close="closeDialog"
	  :close-on-click-modal="false"
	  size="750"
	>
		
		<el-form
			ref="formRef"
			:model="formData"
			:rules="formRules"
			label-width="140px"
		>
		
			<div class="section-title">
			  <span class="title-form_primary">基础设置</span>
			</div>
			
			<el-form-item label="输出源类型" prop="type" >
			  <el-radio-group v-model="formData.type" class="flex-container"  @change="handleDatasourceTypeChange" :loading="loading">
				<el-radio value="OLTP">OLTP</el-radio>
				<!-- <el-radio value="HTTP">HTTP</el-radio> -->
				<el-radio value="MQTT">MQTT</el-radio>
				<el-radio value="REDIS">Redis</el-radio>
				<el-radio value="SERIES">时序数据库</el-radio>
			  </el-radio-group>
			</el-form-item>
			
			<el-form-item label="常量缓存Key" prop="fixedRedisKey" v-if="formData.type=='REDIS'">
			  <el-radio-group v-model="formData.fixedRedisKey">
				<el-radio :value="'0'">否</el-radio>
				<el-radio :value="'1'">是</el-radio>
			  </el-radio-group>
			</el-form-item>
			
			<el-form-item label="缓存取值字段" prop="redisKeyValueField" v-if="formData.type=='REDIS' && formData.fixedRedisKey=='0'">
				<el-input v-model="formData.redisKeyValueField" placeholder="请输入缓存取值字段" />
			</el-form-item>
			
			<el-form-item label="常量缓存Key值" prop="fixedRedisKeyValue" v-if="formData.type=='REDIS' && formData.fixedRedisKey=='1'">
				<el-input v-model="formData.fixedRedisKeyValue" placeholder="请输入常量缓存Key值" />
			</el-form-item>
			
			
			<el-form-item label="缓存数据值类型" prop="redisValueType" v-if="formData.type=='REDIS'">
			  <el-radio-group v-model="formData.redisValueType">
				<el-radio :value="'0'">输出字段对象</el-radio>
				<el-radio :value="'1'">输出字段里某字段</el-radio>
			  </el-radio-group>
			</el-form-item>
			
			<el-form-item label="缓存数据取值字段" prop="redisValueField" v-if="formData.type=='REDIS' && formData.redisValueType=='1'">
				<el-input v-model="formData.redisValueField" placeholder="请输入缓存数据取值字段(必须是输出字段)" />
			</el-form-item>
			
			<el-form-item label="数据源" prop="datasourceId" v-if="formData.type!='REDIS'">
				<el-select v-model="formData.datasourceId" :loading="loading">
					<el-option
					  v-for="item in datasourceOptions"
					  :key="item.id"
					  :label="item.name"
					  :value="item.id"
					/>
				</el-select>
			</el-form-item>
			
			<el-form-item label="数据库表" prop="table" v-if="formData.type=='OLTP'">
				<el-input v-model="formData.table" placeholder="请输入数据库表" />
			</el-form-item>
			
			<el-form-item label="数据库表主键" prop="primarykey" v-if="formData.type=='OLTP'">
				<el-input v-model="formData.primarykey" placeholder="请输入数据库表主键(联合主键英文逗号分隔)" />
			</el-form-item>
			
			<el-form-item label="发布主题" prop="topic" v-if="formData.type=='MQTT'">
				<el-input v-model="formData.topic" placeholder="请输入MQTT发布主题(支持通配:/xxx/${规范字段}/${规范字段})" />
			</el-form-item>
			
			<el-form-item label="QoS等级" prop="qos" v-if="formData.type=='MQTT'">
			  <el-radio-group v-model="formData.qos" class="flex-container">
			    <el-radio value="0">QoS 0</el-radio>
			    <el-radio value="1">QoS 1</el-radio>
				<el-radio value="2">QoS 2</el-radio>
			  </el-radio-group>
			</el-form-item>
			
			<el-form-item label="消息留存" prop="retained" v-if="formData.type=='MQTT'">
			  <el-radio-group v-model="formData.retained" class="flex-container">
			    <el-radio value="0">不留存</el-radio>
			    <el-radio value="1">留存</el-radio>
			  </el-radio-group>
			</el-form-item>
			
			<el-form-item label="表字段和规范一致" prop="fieldStandardSame" >
			  <el-radio-group v-model="formData.fieldStandardSame" class="flex-container" :disabled="formData.type=='SERIES'">
			    <el-radio value="0">不一致</el-radio>
			    <el-radio value="1">一致</el-radio>
			  </el-radio-group>
			</el-form-item>
			
			<div class="section-title" v-if="formData.fieldStandardSame=='0'">
			  <span class="title-form_primary">字段信息</span>
			  <div>
				<el-button type="primary" link @click="handleBatchAddFields">
				  <el-icon><Plus /></el-icon>批量添加字段
				</el-button>
				<el-button type="primary" link @click="handleAddField">
				  <el-icon><Plus /></el-icon>添加字段
				</el-button>
			  </div>
			</div>
			
			<div class="param-model-content" v-if="formData.fieldStandardSame=='0'">
				<draggable
					v-model="fieldDefinitions"
					:animation="150"
					handle=".drag-handle"
					item-key="identifier"
					:component-data="{
					  tag: 'div',
					  type: 'transition-group',
					  name: !drag ? 'flip-list' : null
					}"
					@start="drag = true"
					@end="drag = false"
				>
					<template #item="{ element: row, index }">
					  <div class="param-model-content-row">
						<el-button 
						  class="drag-handle" 
						  link
						>
						  <el-icon><Rank /></el-icon>
						</el-button>
						<div class="param-info">
						  <div class="param-name">输入名:{{ row.inputFieldName }} || 输入标识:{{ row.inputFieldIdentifier }}</div>
						  <div class="param-detail">
							<span>输出名: {{ row.outputFieldName }}</span>
							<span>输出标识: {{ row.outputFieldIdentifier }}</span>
							<el-tag :type="row.outputValueFromInput=='input' ? 'success' : 'info'" size="small">
							  {{ row.outputValueFromInput =='input' ? '输入值' : '默认值' }}
							</el-tag>
						  </div>
						</div>
						<div class="param-actions">
						  <el-button type="primary" link @click="handleEditField(index,row)">
							<el-icon><Edit /></el-icon>编辑
						  </el-button>
						  <el-button type="danger" link @click="removeField(index)">
							<el-icon><Delete /></el-icon>删除
						  </el-button>
						</div>
					  </div>
					</template>
				</draggable>
				<div v-if="fieldDefinitions.length === 0" class="empty-tip">
					暂无字段，请点击上方"添加字段"按钮添加
				</div>
			</div>
		</el-form>
	
		<template #footer>
		  <div class="dialog-footer">
			<el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
			<el-button @click="closeDialog" :loading="loading">取 消</el-button>
		  </div>
		</template>
		<EditOutputFieldDrawer  ref="editOutputFieldDrawerRef" @success="handleEditFieldSuccess"></EditOutputFieldDrawer>
	
	</el-drawer>
</template>

<script lang="ts" setup>
	import { ref } from "vue";
	import type {FormRules } from 'element-plus'
	import { ElMessage } from "element-plus";
	import { reactive } from "vue";
	import { onMounted } from "vue";
	import EditOutputFieldDrawer from '@/components/DataWorkflow/components/EditOutputFieldDrawer.vue'
	import draggable from 'vuedraggable';
	import DatasourceAPI from "@/api/biz/datasource";
	import HttpAPI from "@/api/biz/http";
	import MqttAPI from "@/api/biz/LDMPMqttClient";
	import { ElMessageBox } from "element-plus";
	const emit = defineEmits(['success', 'closed']);
	const loading = ref(false);
	const dialog = ref({
		visible:false,
		title:'',
	});
	const editOutputFieldDrawerRef = ref();
	const datasourceOptions=ref<any>([]);
	const fieldDefinitions = ref<any[]>([]);
	
	const rowIndex = ref<number>(1);
	const formRef=ref();
	const formRules=reactive<FormRules>({
		name: [
			{ required: true, message: "请输入参数名", trigger: "blur" },
			{ min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
		],
		identifier: [
			{ required: true, message: "请输入参数标识", trigger: "blur" },
			{ pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: "标识符必须以字母开头，只能包含字母、数字和下划线", trigger: "blur" }
		],
		type: [
			{ required: true, message: "请选择输入参数类型", trigger: "change" }
		],
		datasourceId: [
			{ required: true, message: "请选择数据源", trigger: "change" }
		],
		fieldStandardSame: [
			{ required: true, message: "请选择表字段和规范是否一致", trigger: "change" }
		],
		table: [
			{ required: true, message: "请输入数据库表名", trigger: "change" }
		],
		primarykey: [
			{ required: true, message: "请输入表主键", trigger: "change" }
		],
		qos: [
			{ required: true, message: "请选择QoS等级", trigger: "change" }
		],
		topic: [
			{ required: true, message: "请输入发布主题", trigger: "change" }
		],
		retained: [
			{ required: true, message: "请选择是否留存消息", trigger: "change" }
		],
		fixedRedisKey: [
			{ required: true, message: "请选择是否使用常量缓存Key", trigger: "change" }
		],
		redisKeyValueField: [
			{ required: true, message: "请输入缓存取值字段", trigger: "change" }
		],
		fixedRedisKeyValue: [
			{ required: true, message: "请输入常量缓存Key值", trigger: "change" }
		],
		redisValueType: [
			{ required: true, message: "请选择缓存数据值类型", trigger: "change" }
		],
		redisValueField: [
			{ required: true, message: "请输入缓存数据取值字段", trigger: "change" }
		],
	});
	
	
	const drag = ref(false);
	//数据源
	const formData=ref<any>({
	});
	
	// const handleDatasourceTypeChange= async ()=>{
	// 	formData.value.datasourceId="";
	// 	datasourceOptions.value=[];
	// 	if('OLTP'==formData.value.type){
	// 		try {
	// 			const data = await DatasourceAPI.options({});
	// 			datasourceOptions.value = data.map((item:any) => ({
	// 				id: item.id,
	// 				name: item.name
	// 			}));
	// 			console.log("OLTP=",data)
	// 		} catch (error:any) {
	// 			console.error(error)
	// 			ElMessage.error('获取OLTP下拉数据失败');
	// 		}
	// 	}
	// 	else if('HTTP'==formData.value.type){
	// 		try {
	// 			const data = await HttpAPI.options({});
	// 			datasourceOptions.value = data.map((item:any) => ({
	// 				id: item.id,
	// 				name: item.name
	// 			}));
	// 			console.log("HTTP=",data)
	// 		} catch (error:any) {
	// 			console.error(error)
	// 			ElMessage.error('获取HTTP下拉数据失败');
	// 		}
	// 	}
	// 	else if('MQTT'==formData.value.type){
	// 		try {
	// 			const data = await MqttAPI.options({});
	// 			datasourceOptions.value = data.map((item:any) => ({
	// 				id: item.id,
	// 				name: item.name
	// 			}));
	// 			console.log("MQTT=",data)
	// 		} catch (error:any) {
	// 			console.error(error)
	// 			ElMessage.error('获取HTTP下拉数据失败');
	// 		}
	// 	}
	// }
	
	const handleDatasourceTypeChange= async ()=>{
		formData.value.datasourceId="";
		getDatasourceTypeChange();
	}
	
	const getDatasourceTypeChange= async ()=>{
		datasourceOptions.value=[];
		if('OLTP'==formData.value.type){
			try {
				const data = await DatasourceAPI.options({src:'OLTP'});
				datasourceOptions.value = data.map((item:any) => ({
					id: item.id,
					name: item.name
				}));
			} catch (error:any) {
				console.error(error)
				ElMessage.error('获取OLTP下拉数据失败');
			}
		}
		else if('HTTP'==formData.value.type){
			try {
				const data = await HttpAPI.options({});
				datasourceOptions.value = data.map((item:any) => ({
					id: item.id,
					name: item.name
				}));
			} catch (error:any) {
				console.error(error)
				ElMessage.error('获取HTTP下拉数据失败');
			}
		}
		else if('MQTT'==formData.value.type){
			try {
				const data = await MqttAPI.options({});
				datasourceOptions.value = data.map((item:any) => ({
					id: item.id,
					name: item.name
				}));
			} catch (error:any) {
				console.error(error)
				ElMessage.error('获取HTTP下拉数据失败');
			}
		}
		
		if('SERIES'==formData.value.type){
			formData.value.fieldStandardSame='0';
			try {
				const data = await DatasourceAPI.options({src:'SERIES'});
				datasourceOptions.value = data.map((item:any) => ({
					id: item.id,
					name: item.name
				}));
			} catch (error:any) {
				console.error(error)
				ElMessage.error('获取时序数据库下拉数据失败');
			}
		}
		
	}
	
	const handleAddField = () => {
		editOutputFieldDrawerRef.value.openDialog(-1,null,standardFields.value,'add',formData.value.type=='SERIES');
	};
	
	const handleEditField = (index: number,data:any) => {
		editOutputFieldDrawerRef.value.openDialog(index,data,standardFields.value,'edit',formData.value.type=='SERIES');
	};
	
	const removeField = (index: number) => {
		ElMessageBox.confirm('确认删除该字段吗？', '提示', {
				type: 'warning'
		}).then(() => {
			fieldDefinitions.value?.splice(index, 1);
			ElMessage.success('删除成功');
		});
	};
	
	const handleEditFieldSuccess=(index:number,data:any)=>{
		try {
			if (!fieldDefinitions.value) {
				fieldDefinitions.value = [];
			}
			if (index > -1) {
				fieldDefinitions.value[index] = data;
			} else {
				fieldDefinitions.value.push(data);
			}
		} catch (e:any) {
			ElMessage.error(e.message);
		}
	}
	
	const standardFields=ref<any>();
	async function openDialog(index: number,_row?: any,definitions?:any, type?: string) {
		if('add'==type){
			rowIndex.value=index;
			dialog.value.visible=true;
			dialog.value.title='新增输出';
			standardFields.value=definitions;
		}else{
			rowIndex.value=index;
			dialog.value.visible=true;
			dialog.value.title='编辑输出';
			formData.value=JSON.parse(JSON.stringify(_row));
			fieldDefinitions.value=formData.value?.fields||[];
			standardFields.value=definitions;
			getDatasourceTypeChange();
		}
	}
	
	const submitForm=()=>{
		formRef.value.validate((isValid: boolean) => {
			if (isValid) {
				loading.value = true;
				formData.value.fields=fieldDefinitions.value;
				emit('success', rowIndex.value, JSON.parse(JSON.stringify(formData.value)));
				loading.value = false;
				closeDialog();
			}
		});
	}
	
	const closeDialog=()=>{
		dialog.value.visible=false;
		dialog.value.title="";
		emit('closed')
		resetForm();
	}
	
	/**
	 * 重置表单
	 */
	function resetForm() {
		formRef.value.resetFields();
		formRef.value.clearValidate();
		formData.value={};
		fieldDefinitions.value=[]
	}	
	
	// 批量添加字段
	const handleBatchAddFields = () => {
		if (!standardFields.value || standardFields.value.length === 0) {
			ElMessage.warning('没有可添加的标准字段');
			return;
		}
		
		ElMessageBox.confirm('是否批量添加所有标准字段？', '提示', {
			type: 'info'
		}).then(() => {
			// 遍历标准字段并添加
			standardFields.value.forEach((field: any) => {
				const newField = {
					// 输入字段信息
					inputFieldName: field.outputFieldName,
					inputFieldIdentifier: field.outputFieldIdentifier,
					inputFieldType: field.outputFieldType,
					inputFieldFormat: field.outputFieldFormat || '',
					inputFieldValueMapping: field.outputFieldValueMapping || 'none',
					inputFieldValueMappingObject: field.outputFieldValueMappingObject || 'none',
					
					// 字段名和标识符相同性
					sameFieldName: '1',
					sameFieldIdentifier: '1',
					
					// 输出字段信息
					outputFieldName: field.outputFieldName,
					outputFieldIdentifier: field.outputFieldIdentifier,
					outputFieldType: field.outputFieldType,
					outputFieldFormat: field.outputFieldFormat || '',
					outputFieldDefaultValue: '',
					outputValueFromInput: 'input'
				};
				
				// 检查是否已存在相同标识符的字段
				const exists = fieldDefinitions.value.some(
					(existingField: any) => existingField.inputFieldIdentifier === field.outputFieldIdentifier
				);
				
				if (!exists) {
					fieldDefinitions.value.push(newField);
				}
			});
			
			ElMessage.success('批量添加成功');
		});
	};
	
	// 生成单个条件组的表达式用于显示
	// const generateGroupExpression = (group: any) => {
	// 	if (!group.conditions?.length) return '';
		
	// 	return group.conditions.map((cond: any, index: number) => {
	// 		let expr = '';
	// 		if (['in', 'not in'].includes(cond.relation)) {
	// 			const values = (cond.values || []).join(',');
	// 			expr = `${cond.relation} (${values})`;
	// 		} else {
	// 			expr = `${cond.relation} ${cond.value}`;
	// 		}
	// 		return index < group.conditions.length - 1 ? `${expr} ${cond.logic}` : expr;
	// 	}).join(' ');
	// };
	
	defineExpose({
	  openDialog,closeDialog
	});
	
	onMounted(() => {
	});
</script>

<style scoped>
.title-form_primary {
	    font-style: normal;
	    font-weight: 500;
	    font-size: 14px;
	    color: #1f2329;
	    position: relative;
	    padding-left: 5px;
	}
	.title-form_primary:before {
	  content: "";
	  width: 2px;
	  height: 14px;
	  background: var(--el-color-primary);
	  position: absolute;
	  top: 50%;
	  transform: translateY(-50%);
	  left: 0;
	}
	
	
	.section-title {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  margin-bottom: 16px;
	}
	
	
	.param-model-content {
	  padding: 16px;
	  background: var(--el-fill-color-light);
	  border-radius: 4px;
	}
	
	.param-model-content-row {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  padding: 12px 8px;
	  margin-bottom: 8px;
	  background: var(--el-bg-color);
	  border: 1px solid var(--el-border-color-lighter);
	  border-radius: 4px;
	  transition: all 0.3s;
	  
	  &:hover {
	    border-color: var(--el-border-color);
	    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	  }
	}
	
	.param-info {
	  flex: 1;
	}
	
	.param-name {
	  font-size: 14px;
	  font-weight: 500;
	  color: var(--el-text-color-primary);
	  margin-bottom: 4px;
	}
	
	.param-detail {
	  display: flex;
	  align-items: center;
	  gap: 16px;
	  color: var(--el-text-color-secondary);
	  font-size: 13px;
	}
	
	.param-actions {
	  display: flex;
	  gap: 8px;
	}
	
	.empty-tip {
	  text-align: center;
	  color: var(--el-text-color-secondary);
	  padding: 32px 0;
	}
	
	.drag-handle {
	  cursor: move;
	  margin-right: 8px;
	  color: var(--el-text-color-secondary);
	  
	  &:hover {
	    color: var(--el-text-color-primary);
	  }
	}
	
	.flip-list-move {
	  transition: transform 0.5s;
	}
	
	.flip-list-enter-active,
	.flip-list-leave-active {
	  transition: all 0.5s;
	}
	
	.flip-list-enter-from,
	.flip-list-leave-to {
	  opacity: 0;
	  transform: translateX(30px);
	}
	
	.condition-content {
	  margin: 20px 0;
	  
	  .empty-tip {
	    text-align: center;
	    padding: 40px 0;
	    color: var(--el-text-color-secondary);
	  }
	
	  .condition-group {
	    margin-bottom: 16px;
	    border: 1px solid var(--el-border-color);
	    border-radius: 8px;
	    overflow: hidden;
	    transition: all 0.3s;
	    
	    &:hover {
	      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	    }
	
	    .group-header {
	      padding: 12px 16px;
	      background-color: var(--el-fill-color-light);
	      border-bottom: 1px solid var(--el-border-color-lighter);
	      display: flex;
	      justify-content: space-between;
	      align-items: center;
	
	      .group-info {
	        display: flex;
	        align-items: center;
	        gap: 8px;
	
	        .group-title {
	          font-weight: 500;
	          color: var(--el-text-color-primary);
	        }
	      }
	
	      .group-actions {
	        display: flex;
	        gap: 12px;
	      }
	    }
	
	    .conditions-list {
	      padding: 16px;
	      background-color: var(--el-bg-color);
	    }
	  }
	
	  .condition-item {
	    margin-bottom: 12px;
	    padding: 12px;
	    border-radius: 4px;
	    background-color: var(--el-fill-color-light);
	    
	    &:last-child {
	      margin-bottom: 0;
	    }
	
	    .condition-row {
	      display: flex;
	      align-items: center;
	      gap: 12px;
	
	      .relation-select {
	        width: 120px;
	      }
	
	      .value-input {
	        flex: 1;
	      }
	    }
	
	    .logic-row {
	      margin-top: 12px;
	      display: flex;
	      justify-content: center;
	
	      .logic-group {
	        .el-radio-button__inner {
	          padding: 8px 20px;
	        }
	      }
	    }
	  }
	}
</style>